package models

import (
	"errors"
	"registration-booking/global"
	"time"
)

type TestDate struct {
	ID
	Date    time.Time `json:"date" gorm:"comment:日期"`
	Num     int       `json:"num" gorm:"comment:数量"`
	Version int       `json:"version" gorm:"comment:版本; default:0"`
	Timestamps
	SoftDeletes
}

func (testDate *TestDate) Update() error {
	testDate.UpdatedAt = time.Now()
	return global.App.DB.Updates(testDate).Error
}

func (testDate *TestDate) Create() error {
	testDate.CreatedAt = time.Now()
	testDate.UpdatedAt = time.Now()
	return global.App.DB.Create(testDate).Error
}

func DeleteTestDateById(id int) error {
	return global.App.DB.Model(TestDate{}).Delete("id = ?", id).Error
}

func FindTestDateList(tomorrow time.Time) (testDate []TestDate, err error) {
	err = global.App.DB.Where("date >= ? AND num > 0", tomorrow).Find(&testDate).Error
	return
}

func FindTextDateById(id uint) (testDate TestDate, err error) {
	err = global.App.DB.Where("id = ? ", id).First(&testDate).Error
	return
}
func UpdateTestDate(testDate TestDate) (err error) {
	if testDate.Num < 0 {
		err = errors.New("预约失败，该日期已约满")
		return
	}
	version := testDate.Version
	testDate.Version = version + 1
	result := global.App.DB.Model(&testDate).Where("id = ? AND version = ?", testDate.ID.ID, version).Updates(&testDate)
	if result.Error != nil {
		err = result.Error
		return
	}
	if result.RowsAffected == 0 {
		err = errors.New("预约失败，请稍后再试")
	}
	return

}

func FindTestDateById(id uint) (testDate TestDate, err error) {
	err = global.App.DB.Where("id = ?", id).First(&testDate).Error
	return
}

func FindDatesPage(tomorrow time.Time, pageNo, pageSize int) (testDates []TestDate, count int64, err error) {
	err = global.App.DB.Model(TestDate{}).Where("date > ?", tomorrow).Count(&count).Offset(pageNo - 1*pageSize).Limit(pageSize).Find(&testDates).Error
	return
}
